package com.roin.learn.activiti.controller;

import com.roin.learn.activiti.base.BaseController;
import com.roin.learn.activiti.base.SysConstent;
import com.roin.learn.activiti.entity.Page;
import com.github.pagehelper.util.StringUtil;
import com.roin.learn.activiti.entity.Position;
import com.roin.learn.activiti.entity.ResourceResult;
import com.roin.learn.activiti.entity.User;
import com.roin.learn.activiti.exception.BusinessException;
import com.roin.learn.activiti.service.PositionService;
import com.roin.learn.activiti.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户维护模块Controller
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController{
    @Resource
    private UserService userService;
    @Resource
    private PositionService positionService;

    @RequestMapping("")
    public String toMain(HttpSession session,Model model){
        checkLogin(session);
        List<Position> positionList = positionService.getAll();
        model.addAttribute("positionList",positionList);
        return "user/main";
    }


    @RequestMapping("add.do")
    @ResponseBody
    public ResourceResult add(User user) {

        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            if (user == null)
                result.setMessage("添加用户失败!user参数为空！");
            else {
                if (StringUtil.isEmpty(user.getUserId()))
                    result.setMessage( "添加用户失败!userId参数为空！");
                if (StringUtil.isEmpty(user.getUserId()))
                    result.setMessage( "添加用户失败!userId参数为空！");
                if (StringUtil.isEmpty(user.getUserName()))
                    result.setMessage( "添加用户失败!userName参数为空！");
                if (StringUtil.isEmpty(user.getUserEmail()))
                    result.setMessage( "添加用户失败!userEmail参数为空！");
                if (StringUtil.isEmpty(user.getUserPassword()))
                    result.setMessage( "添加用户失败!userPassword参数为空！");
                if (user.getPositionId() == null)
                    result.setMessage( "添加用户失败!positionId参数为空！");
            }
            if (StringUtil.isEmpty(result.getMessage())) {
                int row = userService.add(user);
                result.setSuccess(row > 0);
                result.setMessage(row > 0 ? "添加用户成功！" : "添加用户失败!");
            }
        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        }catch (Exception e) {
            result.setMessage(SysConstent.MSG_SYS_ERROR);
            log.error("添加新用户异常",e);
        }
        return result;
    }


    @RequestMapping("deleteByUserIds.do")
    @ResponseBody
    public ResourceResult delete(String[] ids) {
        ResourceResult result = new ResourceResult();
        if (ids==null || ids.length==0)
            result.setMessage( "删除用户失败!ids参数为空！");
        if (StringUtil.isEmpty(result.getMessage())) {
            int row = userService.deleteByUserIds(ids);
            result.setSuccess(row > 0);
            if (row==0)
                result.setMessage("删除用户失败!");
            else if (ids.length!=row) {
                result.setMessage(String.format("共删除%s条数据，删除失败%s条！", row, ids.length - row));
                result.setSuccess(true);
            }
            else {
                result.setMessage("删除用户成功!");
                result.setSuccess(true);
            }
        }
        return result;

    }

    @RequestMapping("update.do")
    @ResponseBody
    public ResourceResult update(User user) {
        ResourceResult result = new ResourceResult();
        if (user == null)
            result.setMessage( "修改用户失败!参数为空！");
        else{
            if (user.getId()==null)
                result.setMessage( "修改用户失败!Id参数为空！");
            if (StringUtil.isEmpty(user.getUserId()))
                result.setMessage( "修改用户失败!userId参数为空！");
            if (StringUtil.isEmpty(user.getUserId()))
                result.setMessage( "修改用户失败!userId参数为空！");
            if (StringUtil.isEmpty(user.getUserName()))
                result.setMessage( "修改用户失败!userName参数为空！");
            if (StringUtil.isEmpty(user.getUserEmail()))
                result.setMessage( "修改用户失败!userEmail参数为空！");
            if (StringUtil.isEmpty(user.getUserPassword()))
                result.setMessage( "修改用户失败!userPassword参数为空！");
            if (user.getPositionId() == null)
                result.setMessage( "修改用户失败!positionId参数为空！");
        }
        if (StringUtil.isEmpty(result.getMessage())) {
            int row = userService.update(user);
            result.setSuccess(row > 0);
            result.setMessage(row > 0 ? "修改用户成功！" : "修改用户失败!");
        }

        return result;
    }

    @RequestMapping("getById.do")
    @ResponseBody
    public ResourceResult getById(@RequestParam("id") Integer id) {
        ResourceResult result = new ResourceResult();
        User user = userService.getById(id);
        if (user==null)
            result.setMessage("找不到ID为"+id+"用户");
        else {
            result.setSuccess(true);
            result.setData(user);
        }
        return result;
    }

    @RequestMapping("list.json")
    @ResponseBody
    public Object getPage(Integer pageNum, Integer pageSize) {
        Page<User> page = userService.getDtoPage(pageNum, pageSize, null);
        return page;
    }

    /**
     * 与Activiti用户同步
     * 同步原则：1，业务用户表里有Activiti用户表时没有的用户，添加到Activiti用户表
     * 2,业务用户表里没有Activiti用户表时有的用户，删除到Activiti用户表中业务用户表里没有的用户
     * 3,Activiti用户表里对应业务用户表里的用户，如果属性值不一致，以业务用户表里的用户为准更新
     * @return
     */
    @RequestMapping("syncUser.do")
    @ResponseBody
    public ResourceResult syncUser(){
        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            userService.syncUser();
            result.setMessage("同步成功！").setSuccess(true);
        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        }catch (Exception e) {
            result.setMessage(SysConstent.MSG_SYS_ERROR);
            log.error("同步用户异常",e);
        }
        return result;
    }
}
